import { observable, action, computed, autorun } from 'mobx'

class TodoStore {
  @observable todos = [];
  @observable filter = 'all'

  @computed get unFinishedTodoCount() {
    return this.todos.filter(todo => !todo.isCompleted).length
  }

  @action.bound todoAdd(taskName) {
    this.todos.push({
      taskName,
      isCompleted: false
    })
  }

  @action.bound todoDelete(index) {
    const newTodos = [...this.todos]

    newTodos.splice(index, 1)

    this.todos = newTodos
  }

  @action.bound changeCompleted(index, flag) {
    const todo = this.todos[index]

    todo.isCompleted = flag
  }

  @action.bound changeFilter(condition) {
    this.filter = condition
  }

  @action.bound todoClearCompleted() {
    this.todos = this.todos.map(todo => ({
      ...todo,
      isCompleted: false
    }))
  }

  @computed get filterTodo() {
    switch (this.filter) {
      case 'All':
        return this.todos;
      case 'Active':
        return this.todos.filter(item => !item.isCompleted)
      case 'Completed':
        return this.todos.filter(item => item.isCompleted)
    }

    return this.todos
  }
}

const todo = new TodoStore()

export default todo